var hot_alarm_map = function () {
    for(var i in this.alarms){
        var key = 
        {
            alarm_type: NumberInt(this.alarms[i].alarm_type)
        };
        var values = {
            point_list : this.coordinates,
            alarm_count:1
            
        };
        emit(key, values);
    }
};
var hot_alarm_reduce = function (key, values) {
    const reduce_result = {
        point_list: [],
        alarm_count: 0
    };
    values.forEach(
        function (val) {
        reduce_result.point_list = reduce_result.point_list.concat(val.point_list);
        reduce_result.alarm_count+=val.alarm_count;
    })
    return reduce_result;
};

var hot_alarm_finalize = function (key, values) {
    var _result_coordinates = [];
	if(values.alarm_count==1){
            var obj = values.point_list;
            values.point_list=null;
            var list =new Array();
            list.push(obj);
            values.point_list=list;
    }
    if(values.alarm_count>20000){
        var n=NumberInt(values.alarm_count/10000);
        for (var i in values.point_list) {
            if(i%n==0){
                if(values.point_list[i]){
                    if(values.point_list[i]){
						_result_coordinates.push(values.point_list[i]);
					}
                }
                
            }   
        }   
    }else{
        for (var i in values.point_list) {
            if(i<10001){
				if(values.point_list[i]){
					_result_coordinates.push(values.point_list[i]);
				}
                
            }   
        }
    }
	values.point_list=[]
    values.coordinates=_result_coordinates;
    values.alarm_count=NumberInt(values.alarm_count);
    return values;
};


db.runCommand({
    mapReduce: 'alarm_info_170927',
    map: hot_alarm_map,
    reduce: hot_alarm_reduce,
    finalize: hot_alarm_finalize,
    out: 'vehicle_hot_swap_alarm',
    sort:{_id:1},
    query: {
    }
});